# -*- coding: UTF-8 -*-
import logging
import time
import json
import paho.mqtt.client as mqtt
from threading import Timer
from mysqltest.mysql_db import sqlconnect

# MQTT配置
MQTT_SERVER = "172.16.1.29"
MQTT_PORT = 18832
username = "intranet"
password = "gst@2024_123!"
topic = "IOT/intranet/client/request/prod/"
publish_topic = "IOT/intranet/server/report/prod/"

# 配置日志
logging.basicConfig(
  level=logging.INFO,
  format='%(asctime)s - %(levelname)s - %(message)s',
  handlers=[
    logging.FileHandler('server.log'),
    logging.StreamHandler()
  ]
)
log = logging.getLogger(__name__)

client = mqtt.Client()
client.username_pw_set(username=username, password=password)
client.on_connect = lambda client, userdata, flags, rc: log.info("成功连接到MQTT代理！") if rc == 0 else log.error(
  "连接失败")

# 存储每个设备的定时器（字典：{imei: Timer}）
device_timers = {}


def on_connect(client, userdata, flags, rc):
  if rc == 0:
    log.info("成功连接到MQTT代理！")
    client.subscribe(topic)
    # 连接后初始化所有设备的定时器
    initialize_device_timers()
  else:
    log.error(f"连接失败，错误码: {rc}")


def initialize_device_timers():
  """从数据库获取设备列表并初始化定时器"""
  global device_timers
  sql = "SELECT device_code FROM device WHERE is_del = 0 AND dept_id = 1"
  sql_result = sqlconnect.sqljudje(sql)
  device_list = [sub[0] for sub in sql_result]

  for imei in device_list:
    start_device_timer(imei)  # 为每个设备启动定时器


def start_device_timer(imei):
  """启动/重置单个设备的定时器"""

  def timer_callback():
    """定时器回调函数：发布消息并重启定时器"""
    pub_topic = f"{publish_topic}{imei}"
    response1 = {
      "baud": 57600,
      "cmd": "hello",
      "decibel": "0.0",
      "flashSpace": "44824",
      "imei": imei,
      "intervalTime": 10,
      "playContent": "",
      "playInfo": {"content": ""},
      "playStatus": 0,
      "rsWriteInfo": {
        "callType": -1,
        "character": "",
        "command": "",
        "identification": ""
      },
      "sdcardSpace": "7684500",
      "storageType": 1,
      "v12": 0,
      "v24": 0,
      "v5": 1,
      "volume": 7,
      "volumeAdaptSchema": {
        "calcCycle": 0,
        "frequency": 0,
        "monitorStatus": 0,
        "schema": []
      },
      "topic": pub_topic
    }

    client.publish(pub_topic, json.dumps(response1))
    log.info(f"设备 {imei} 发布: {response1} 到 {pub_topic}")

    # 重启定时器（每10秒一次）
    start_device_timer(imei)

  # 取消已存在的定时器（避免重复）
  if imei in device_timers and device_timers[imei].is_alive():
    device_timers[imei].cancel()

  # 创建新定时器
  timer = Timer(10, timer_callback)
  timer.start()
  device_timers[imei] = timer


def hello():
  client.on_connect = on_connect
  client.connect(MQTT_SERVER, MQTT_PORT, 60)
  client.loop_start()  # 启动MQTT网络循环

  try:
    while True:
      time.sleep(1)  # 保持主线程运行
  except KeyboardInterrupt:
    log.info("\n接收到中断信号，停止所有定时器...")
    # 清理所有定时器
    for timer in device_timers.values():
      timer.cancel()
    client.loop_stop()
    client.disconnect()

if __name__ == "__main__":

 hello()